package server;

import java.awt.Polygon;

import net.*;

/**
 * Processes incoming NXT commands.
 * 
 * Returns 0 on success, -1 on error.
 */
public class NXTCommands {
	
	private final NetCommand command;
	private NetConnection iPhoneConnection;
	public ServiceManager serviceManager;
	
	public NXTCommands(NetCommand command, NetConnection connection){
		this.command = command;
		this.iPhoneConnection = connection;
	}
	
	public int execute() {
		// read command head
		String head = this.command.getHead();
		String body = this.command.getBody();
		
		// error catching
		int result = -1;
		
		/**
		 * // NXT -> Server
		 * PING // Verbindung checken.
		 * SCRS <angle> <distance> // Entfernungsmessung.
		 * TRRS <motor> <speed> ... // Aktuelle Geschw. der Motoren.
		 * ANGL <motor> <angle> // Winkel eines Motors.
		 * BUMP // Kollision. 
		 */
		// PING // Verbindung checken.
		if (head.equals("PING")) {
			// TODO // Low priority
			result = 0;
		} 
		// SCRS <angle> <distance> // Entfernungsmessung.
		else if (head.equals("SCRS")) {
			System.out.println("Dist: " + command.getBody());
			iPhoneConnection.sendMessage(command.toMessage());
			//adjustRadarData(body);
			result = 0;
		} 
		// TRRS <motor> <speed> ... // Aktuelle Geschw. der Motoren.
		else if (head.equals("TRRS")) {
			// TODO // Low priority
			result = 0;
		} 
		// ANGL <motor> <angle> // Winkel eines Motors.
		else if (head.equals("ANGL")) {
			// TODO // Low priority
			result = 0;
		} 
		// BUMP // Kollision. 
		else if (head.equals("BUMP")) {
			NetMessage message = new NetMessage("BUMP\n");
			iPhoneConnection.sendMessage(message);
			System.out.println("BUMP");
			result = 0;
		}
		
		return result;
	}

	private void adjustRadarData(String body) {
		int iAngle = 0;
		int iDistance = 0;
		
		String sAngle = "";
		String sDistance = "";
		
		Polygon p = serviceManager.gui.radar_polygon;
		
		sAngle = sAngle.substring(0, sAngle.indexOf(" "));
		sDistance = sDistance.substring(sDistance.indexOf(" ")+1, sDistance.length());
		
		try {
			iAngle = Integer.parseInt(sAngle);
			iDistance = Integer.parseInt(sDistance);
			
			int iAlpha = 90 - iAngle;
			
			int new_x = (int) (Math.sin(iAlpha) * iDistance);
			int new_y = (int) (Math.cos(iAlpha) * iDistance);
			
			p.xpoints[iAngle+60] = new_x;
			p.ypoints[iAngle+60] = new_y;
			
		} catch (NumberFormatException e) {  }
	}
}